package com.banciyuan.bcywebview.biz.post.cos;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.detail.complex.ComplexDetailActivity;
import com.banciyuan.bcywebview.biz.post.pic.HttpImageAdapter;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.PostItem;

/**
 * Created by squall on 2016/2/22.
 */
public class CosEditActivity extends CosPostActivity {

    private DetailType detailData;
    private HttpImageAdapter httpImageAdapter;
    private final static int NOEDIT = 4301;

    @Override
    protected void initArgs() {
        super.initArgs();
        edit = true;
        from_memory = true;
        detailData = (DetailType) getIntent().getSerializableExtra("edit_data");
    }

    @Override
    protected void initUi() {
        super.initUi();
        getEdit();
        ((TextView) findViewById(R.id.info_text)).setText(getString(R.string.add_title_cos_no_tags));
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                getEdit();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void getEdit() {
        String url = HttpUtils.BASE_URL + CoserApi.getEditcos();
        List<BcyPair> pairs = new ArrayList<BcyPair>();
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairs.add(new BcyPair(HttpUtils.CPID, detailData.getCp_id()));
        pairs.add(new BcyPair(HttpUtils.RPID, detailData.getRp_id()));
        HashMap<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (StatusCodeUtils.dealStatusCode(s, CosEditActivity.this)) {
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        postItem = gson.fromJson(result, new TypeToken<PostItem>() {
                        }.getType());
                        renderData();
                    } else {
                        int status = jsonObject.getInt(HttpUtils.UPLOAD_STATUS);
                        if (status == NOEDIT) {
                            mProgressbarHelper.onNodata(getString(R.string.no_edit));
                        }
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
            }
        };
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(requestParam);
    }

    private void renderData() {
        setItem();
        httpImageAdapter = new HttpImageAdapter(postItem.getMulti(), this);
        noScrollRecycler.setAdapter(httpImageAdapter);
        mProgressbarHelper.onSuccess();
        edit_warn.setVisibility(View.VISIBLE);
    }

    private void commit() {
        if (!vaild()) return;
        if (!this.isFinishing()) {
            mDialog.show();
        }
        String url = HttpUtils.BASE_URL + CoserApi.getDoeditcos();
        List<BcyPair> pairs = new ArrayList<BcyPair>();
        String json = getPostJson(postItem.getMulti());
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairs.add(new BcyPair(HttpUtils.CPID, detailData.getCp_id()));
        pairs.add(new BcyPair(HttpUtils.RPID, detailData.getRp_id()));
        pairs.add(new BcyPair(HttpUtils.UPLOAD_DATA, json));
        HashMap<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (!CosEditActivity.this.isFinishing()) {
                    mDialog.dismiss();
                }
                try {
                    if (StatusCodeUtils.dealStatusCode(s, CosEditActivity.this)) {
                        Intent intent = new Intent();
                        intent.setClass(CosEditActivity.this, ComplexDetailActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra(MyConstants.CPIDVALUE, detailData.getCp_id());
                        intent.putExtra(MyConstants.RPIDVALUE, detailData.getRp_id());
                        intent.putExtra(MyConstants.TIMELINETYPE, TimelineFactory.TIMELINE_TYPE_COSER);
                        startActivity(intent);
                    }
                } catch (Exception e) {
                    MyToast.show(CosEditActivity.this, getString(R.string.modify_fail));
                }
            }
        };
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                MyToast.show(CosEditActivity.this, getString(R.string.modify_fail));
                if (!CosEditActivity.this.isFinishing()) {
                    mDialog.dismiss();
                }
            }
        };
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(stringRequestParam);
    }

    @Override
    protected void initActionbar() {
        super.initActionbar();
        mActionbarHelper.setTitle(getString(R.string.edit_cos));
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.rl_add_character:
                addCharater();
                break;
            case R.id.ll_rights_set:
                saveItem();
                intent.setClass(CosEditActivity.this, CosRightsActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, postItem);
                startActivityForResult(intent, GO_SETRIGHTS);
                break;
            case R.id.ll_info_set:
                saveItem();
                intent.setClass(CosEditActivity.this, CosInfoActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, postItem);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, false);
                startActivityForResult(intent, GO_SETINFO);
                break;
            case R.id.base_action_bar_home_text_item:
                commit();
                break;
        }
    }
}
